<template>
  <view class="fund-page">
    <!-- 基金统计 -->
    <view class="fund-stats">
      <view class="stats-item">
        <text class="stats-value">{{ totalAmount }}</text>
        <text class="stats-label">总基金金额</text>
      </view>
      <view class="stats-item">
        <text class="stats-value">{{ totalDonors }}</text>
        <text class="stats-label">总项目</text>
      </view>
      <view class="stats-item">
        <text class="stats-value">{{ totalProjects }}</text>
        <text class="stats-label">进行项目</text>
      </view>
    </view>

    <!-- 三修项目 -->
    <view class="fund-projects">
      <view class="project-section">
        <view class="section-header">
          <view class="section-title">修谱项目</view>
          <view class="section-more" @click="viewMore('修谱')">查看更多</view>
        </view>
        <view class="project-list">
          <view
            v-for="(project, index) in genealogyProjects"
            v-if="genealogyProjects.length > 0"
            :key="index"
            class="project-item"
            @click="viewProjectDetail(project)"
          >
            <image
              class="project-image"
              :src="project.image || 'https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/6dbd9f9fdab44ca4a6409ad787126bb3.png'"
              mode="aspectFill"
            />
            <view class="project-info">
              <view class="project-name">{{ project.projectName }}</view>
              <view class="project-progress">
                <wd-progress :percentage="calculateProgress(project)" :show-text="false" />
                <view class="progress-text">
                  <text>已筹：¥{{ formatNumber(project.raisedFund) }}</text>
                  <text>目标：¥{{ formatNumber(project.targetFund) }}</text>
                </view>
              </view>
              <view class="project-desc">{{ project.projectIntro }}</view>
            </view>
          </view>
          <view v-else class="empty-state">
            <text>暂无项目数据</text>
            <view class="add-more-btn" @click="viewMore('修谱')">加载更多</view>
          </view>
        </view>
      </view>

      <view class="project-section">
        <view class="section-header">
          <view class="section-title">修墓项目</view>
          <view class="section-more" @click="viewMore('修墓')">查看更多</view>
        </view>
        <view class="project-list">
          <view
            v-for="(project, index) in tombProjects"
            v-if="tombProjects.length > 0"
            :key="index"
            class="project-item"
            @click="viewProjectDetail(project)"
          >
            <image
              class="project-image"
              :src="project.image || 'https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/9780ab19c86840c086e361eb576940b1.png'"
              mode="aspectFill"
            />
            <view class="project-info">
              <view class="project-name">{{ project.projectName }}</view>
              <view class="project-progress">
                <wd-progress :percentage="calculateProgress(project)" :show-text="false" />
                <view class="progress-text">
                  <text>已筹：¥{{ formatNumber(project.raisedFund) }}</text>
                  <text>目标：¥{{ formatNumber(project.targetFund) }}</text>
                </view>
              </view>
              <view class="project-desc">{{ project.projectIntro }}</view>
            </view>
          </view>
          <view v-else class="empty-state">
            <text>暂无项目数据</text>
            <view class="add-more-btn" @click="viewMore('修墓')">加载更多</view>
          </view>
        </view>
      </view>

      <view class="project-section">
        <view class="section-header">
          <view class="section-title">修祠项目</view>
          <view class="section-more" @click="viewMore('修祠')">查看更多</view>
        </view>
        <view class="project-list">
          <view
            v-for="(project, index) in templeProjects"
            v-if="templeProjects.length > 0"
            :key="index"
            class="project-item"
            @click="viewProjectDetail(project)"
          >
            <image
              class="project-image"
              :src="project.image || 'https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/8de8503736f244718c1dd3c2abd042b3.png'"
              mode="aspectFill"
            />
            <view class="project-info">
              <view class="project-name">{{ project.projectName }}</view>
              <view class="project-progress">
                <wd-progress :percentage="calculateProgress(project)" :show-text="false" />
                <view class="progress-text">
                  <text>已筹：¥{{ formatNumber(project.raisedFund) }}</text>
                  <text>目标：¥{{ formatNumber(project.targetFund) }}</text>
                </view>
              </view>
              <view class="project-desc">{{ project.projectIntro }}</view>
            </view>
          </view>
          <view v-else class="empty-state">
            <text>暂无项目数据</text>
            <view class="add-more-btn" @click="viewMore('修祠')">加载更多</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 捐赠说明 -->
    <view class="fund-guide">
      <view class="section-title">捐赠说明</view>
      <view class="guide-content">
        <view class="guide-item">
          <text class="guide-title">1. 捐赠方式</text>
          <text class="guide-text">支持微信支付、支付宝等多种支付方式</text>
        </view>
        <view class="guide-item">
          <text class="guide-title">2. 捐赠用途</text>
          <text class="guide-text">所有捐赠将用于修谱、修墓、修祠等家族公益项目</text>
        </view>
        <view class="guide-item">
          <text class="guide-title">3. 捐赠证书</text>
          <text class="guide-text">捐赠后将获得电子捐赠证书，可下载保存</text>
        </view>
      </view>
    </view>

    <!-- 捐赠按钮 -->
    <!-- <view class="donate-button">
      <wd-button type="primary" block @click="showDonateModal">立即捐赠</wd-button>
    </view> -->

    <!-- 捐赠弹窗 -->
    <wd-popup v-model="showModal" position="bottom">
      <view class="donate-modal">
        <view class="modal-header">
          <text class="modal-title">选择捐赠项目</text>
          <wd-icon name="close" @click="showModal = false" />
        </view>
        <view class="modal-content">
          <view class="project-select">
            <view class="select-title">选择项目类型</view>
            <view class="select-list">
              <view
                v-for="(type, index) in projectTypes"
                :key="index"
                class="select-item"
                :class="{ active: selectedType === type.value }"
                @click="selectedType = type.value"
              >
                {{ type.label }}
              </view>
            </view>
          </view>
          <view class="amount-list">
            <view
              v-for="(amount, index) in presetAmounts"
              :key="index"
              class="amount-item"
              :class="{ active: selectedAmount === amount }"
              @click="selectedAmount = amount"
            >
              {{ amount }}元
            </view>
            <view class="amount-item custom">
              <input
                v-model="customAmount"
                type="number"
                placeholder="其他金额"
                @input="handleCustomAmount"
              />
            </view>
          </view>
          <view class="donate-message">
            <input v-model="donateMessage" type="text" placeholder="请输入捐赠留言（选填）" />
          </view>
        </view>
        <view class="modal-footer">
          <wd-button type="primary" block @click="handleDonate">确认捐赠</wd-button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { getFundProjectPage, type FundProject } from "@/api/fund";

// 统计数据
const totalAmount = ref("¥0");
const totalDonors = ref(0);
const totalProjects = ref(0);

// 项目数据
const allProjects = ref<FundProject[]>([]);
const genealogyProjects = computed(() =>
  allProjects.value.filter((p) => p.projectType === "修谱").slice(0, 2)
);
const tombProjects = computed(() =>
  allProjects.value.filter((p) => p.projectType === "修墓").slice(0, 2)
);
const templeProjects = computed(() =>
  allProjects.value.filter((p) => p.projectType === "修祠").slice(0, 2)
);

// 加载项目数据
const loadProjects = async () => {
  try {
    const res = await getFundProjectPage(1, 10);
    if (res && res.list) {
      allProjects.value = res.list;

      // 更新统计数据
      let total = 0;
      const donorSet = new Set();

      allProjects.value.forEach((project) => {
        total += project.raisedFund || 0;

        // 解析progressArray，可能包含捐赠者数据
        try {
          const progress = JSON.parse(project.progressArray || "[]");
          // 这里根据实际返回的progressArray格式进行处理
          // 从示例数据看是包含日期和内容的进度更新，而不是捐赠者
          progress.forEach((item: any) => {
            if (item.date) {
              // 这里只是记录进度更新次数，实际应该根据真实数据调整
              donorSet.add(item.date);
            }
          });
        } catch (e) {
          console.error("解析项目进度数据失败", e);
        }
      });

      totalAmount.value = `¥${formatNumber(total)}`;
      totalDonors.value = donorSet.size || allProjects.value.length * 3; // 如果没有真实数据，使用模拟数据
      totalProjects.value = allProjects.value.length;
    }
  } catch (error) {
    console.error("获取基金项目数据失败", error);
  }
};

// 格式化数字
const formatNumber = (num: number) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 计算进度
const calculateProgress = (project: FundProject) => {
  if (!project.targetFund || project.targetFund === 0) return 0;
  const progress = (project.raisedFund / project.targetFund) * 100;
  return Math.min(100, Math.max(0, Math.round(progress)));
};

// 项目类型
const projectTypes = [
  { label: "修谱项目", value: "修谱" },
  { label: "修墓项目", value: "修墓" },
  { label: "修祠项目", value: "修祠" },
];

// 捐赠弹窗相关
const showModal = ref(false);
const selectedType = ref("修谱");
const selectedAmount = ref(0);
const customAmount = ref("");
const donateMessage = ref("");
const presetAmounts = [100, 500, 1000, 2000, 5000];

// 查看更多
const viewMore = (type: string) => {
  uni.navigateTo({
    url: `/pages/work/fund/list?type=${type}`,
  });
};

// 查看项目详情
const viewProjectDetail = (project: FundProject) => {
  uni.navigateTo({
    url: `/pages/work/fund/detail?id=${project.id}`,
  });
};

// 显示捐赠弹窗
const showDonateModal = () => {
  showModal.value = true;
};

// 处理自定义金额输入
const handleCustomAmount = (e: any) => {
  const value = e.detail.value;
  if (value) {
    selectedAmount.value = 0;
  }
};

// 处理捐赠
const handleDonate = () => {
  const amount = selectedAmount.value || Number(customAmount.value);
  if (!amount) {
    uni.showToast({
      title: "请选择或输入捐赠金额",
      icon: "none",
    });
    return;
  }

  // TODO: 调用支付接口
  uni.showLoading({
    title: "处理中...",
  });

  setTimeout(() => {
    uni.hideLoading();
    showModal.value = false;
    uni.showToast({
      title: "捐赠成功",
      icon: "success",
    });
  }, 1500);
};

// 初始化
onMounted(() => {
  loadProjects();
});
</script>

<style lang="scss">
.fund-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.fund-stats {
  display: flex;
  justify-content: space-around;
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;

  .stats-item {
    text-align: center;

    .stats-value {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #1989fa;
      margin-bottom: 10rpx;
    }

    .stats-label {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.project-section {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .section-more {
      font-size: 26rpx;
      color: #1989fa;
    }
  }
}

.project-list {
  .project-item {
    display: flex;
    margin-bottom: 30rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .project-image {
      width: 200rpx;
      height: 150rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }

    .project-info {
      flex: 1;

      .project-name {
        font-size: 30rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 10rpx;
      }

      .project-progress {
        margin-bottom: 10rpx;

        .progress-text {
          display: flex;
          justify-content: space-between;
          font-size: 24rpx;
          color: #666;
          margin-top: 6rpx;
        }
      }

      .project-desc {
        font-size: 26rpx;
        color: #666;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }
    }
  }
}

.fund-guide {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .guide-content {
    .guide-item {
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .guide-title {
        display: block;
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 10rpx;
      }

      .guide-text {
        font-size: 26rpx;
        color: #666;
        line-height: 1.6;
      }
    }
  }
}

.donate-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.donate-modal {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .modal-content {
    .project-select {
      margin-bottom: 30rpx;

      .select-title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 20rpx;
      }

      .select-list {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -10rpx;

        .select-item {
          width: calc(33.33% - 20rpx);
          height: 80rpx;
          line-height: 80rpx;
          text-align: center;
          background-color: #f5f5f5;
          border-radius: 8rpx;
          margin: 10rpx;
          font-size: 28rpx;
          color: #333;

          &.active {
            background-color: #1989fa;
            color: #fff;
          }
        }
      }
    }

    .amount-list {
      display: flex;
      flex-wrap: wrap;
      margin: 0 -10rpx;
      margin-bottom: 30rpx;

      .amount-item {
        width: calc(33.33% - 20rpx);
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        margin: 10rpx;
        font-size: 28rpx;
        color: #333;

        &.active {
          background-color: #1989fa;
          color: #fff;
        }

        &.custom {
          input {
            width: 100%;
            height: 100%;
            text-align: center;
            font-size: 28rpx;
          }
        }
      }
    }

    .donate-message {
      input {
        width: 100%;
        height: 80rpx;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
      }
    }
  }

  .modal-footer {
    margin-top: 30rpx;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  text-align: center;
  height: 150rpx;

  text {
    color: #999;
    font-size: 28rpx;
    margin-bottom: 20rpx;
  }

  .add-more-btn {
    margin-top: 20rpx;
    padding: 10rpx 30rpx;
    background-color: #1989fa;
    color: #fff;
    border-radius: 30rpx;
    font-size: 26rpx;
  }
}
</style>
